//
//  QYPhotos.swift
//  QYPhotos
//
//  Created by Joggy on 16/4/28.
//  Copyright © 2016年 Joggy. All rights reserved.
//

import UIKit
import Photos

@objc protocol QYPhotosDelegate {
    func selectedPhotos(_ photos: [UIImage])
}

class QYPhotos: UIViewController {
    
    let spacing: CGFloat = 3
    let reuseIdentifier = "qyCell"
    
    fileprivate let screenWidth = UIScreen.main.bounds.width
    fileprivate let screenHeight = UIScreen.main.bounds.height

    fileprivate var photos: PHFetchResult<PHAsset>!
    fileprivate var selectedAsset = [Bool]()
    fileprivate var collectionView: UICollectionView!
    fileprivate var flowLayout: UICollectionViewFlowLayout!
    var delegate: QYPhotosDelegate!
    
    //setting
    fileprivate var numberOfSelected: Int = 1
    fileprivate var currentNumberOfSelected: Int = 0
    fileprivate var barItemColor = UIColor.white
    fileprivate var barTintColor = UIColor.blue
    
    fileprivate var lineOfItem: Int = 0
    fileprivate var withOfItem: CGFloat = 65
    
    fileprivate var leftButton: UIButton!
    fileprivate var rightButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        prepareForNav()
        prepareForLayout()
    }
    
    fileprivate func prepareForNav() {
        self.navigationController?.navigationBar.isTranslucent = false
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: barItemColor]
        self.navigationController?.navigationBar.barTintColor = barTintColor
        self.title = "相机胶卷"
        leftButton = UIButton(type: UIButtonType.system)
        leftButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        leftButton.layer.position = CGPoint(x: 22, y: 22)
        leftButton.setTitle("取消", for: UIControlState())
        leftButton.setTitleColor(barItemColor, for: UIControlState())
        leftButton.addTarget(self, action: #selector(dismisss), for: UIControlEvents.touchUpInside)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
        rightButton = UIButton(type: UIButtonType.system)
        rightButton.frame = CGRect(x: 0, y: 0, width: 88, height: 44)
        rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right
        rightButton.layer.position = CGPoint(x: screenWidth - 22, y: 22)
        rightButton.setTitle("选择(0)", for: UIControlState())
        rightButton.setTitleColor(barItemColor, for: UIControlState())
        rightButton.addTarget(self, action: #selector(selectPhotos), for: UIControlEvents.touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
    }
    
    fileprivate func prepareForLayout() {
        flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = spacing
        flowLayout.minimumInteritemSpacing = spacing
        flowLayout.itemSize = CGSize(width: (screenWidth - 5*spacing)/4, height: (screenWidth - 5*spacing)/4)
        flowLayout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight - 64), collectionViewLayout: flowLayout)
        collectionView.backgroundColor = UIColor.white
        collectionView.register(QYPhotosCell.classForCoder(), forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        self.view.addSubview(collectionView)
        currentNumberOfSelected = 0
    }
    
    //MARK: -事件方法
    
    func setSelectNumber(_ number: Int) {
        self.numberOfSelected = number
    }
    
    func setBarItemColor(_ color: UIColor) {
        self.barItemColor = color
    }
    
    func setBarTintColor(_ color: UIColor) {
        self.barTintColor = color
    }
    
    func showPhotos(_ viewController: UIViewController) {
        let photoAuthorState = PHPhotoLibrary.authorizationStatus().rawValue
        if photoAuthorState == 0 {
            PHPhotoLibrary.requestAuthorization({ (status) in
                print(status.rawValue)
                switch status {
                case .authorized:
                    self.presentPhotoView(viewController)
                    break
                default:
                    break
                }
            })
        }
        else {
            switch photoAuthorState {
            case 2:
                let alter = UIAlertController(title: "访问被拒绝", message: "请在'设置->隐私->照片'中允许访问相册", preferredStyle: UIAlertControllerStyle.alert)
                alter.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil))
                alter.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.default, handler: nil))
                viewController.present(alter, animated: true, completion: nil)
                break
            case 3:
                presentPhotoView(viewController)
                break
            default:
                break
            }
        }
    }
    
    func presentPhotoView(_ viewController: UIViewController) {
        self.getPhotos()
        let photosNav = UINavigationController(rootViewController: self)
        viewController.present(photosNav, animated: true, completion: nil)
    }
    
    func selectPhotos() {
        var images = [UIImage]()
        let manger = PHImageManager.default()
        let options = PHImageRequestOptions()
        options.version = PHImageRequestOptionsVersion.original
        options.deliveryMode = PHImageRequestOptionsDeliveryMode.opportunistic
        options.resizeMode = PHImageRequestOptionsResizeMode.fast
        options.isSynchronous = true
        for i in 0...self.selectedAsset.count - 1 {
            if selectedAsset[i] {
                manger.requestImageData(for: photos.object(at: i) as! PHAsset, options: options, resultHandler: { (data, str, ori, info) -> Void in
                    let image = UIImage(data: data!)
                    let leng = CGFloat(data!.count)/(1000.0*1000)
                    var scal: CGFloat = 1
                    if leng > 3 {
                        scal = 0.1
                    }
                    else if leng > 1 {
                        scal = 0.3
                    }
                    else if leng > 0.5 {
                        scal = 0.5
                    }
                    else {
                        scal = 1
                    }
                    let data1 = UIImageJPEGRepresentation(image!, scal)
                    let image1 = UIImage(data: data1!)
                    images.append(image1!)
                })
            }
        }
        delegate.selectedPhotos(images)
        self.dismiss(animated: true, completion: nil)
    }
    
    func dismisss() {
        self.dismiss(animated: true, completion: nil)
    }
    
    fileprivate func getPhotos() {
        self.photos = PHAsset.fetchAssets(with: nil)
        self.selectedAsset = [Bool](repeating: false, count: self.photos.count)
    }
    
    fileprivate func showError() {
        let alert = UIAlertController(title: "错误", message: "最多选择取\(numberOfSelected)张", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.cancel, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension QYPhotos: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1;
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.photos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! QYPhotosCell
        if cell.selectButton.isSelected {
            cell.selectButton.isSelected = false
            currentNumberOfSelected -= 1
            rightButton.setTitle("选择(\(currentNumberOfSelected))", for: UIControlState())
        }
        else if currentNumberOfSelected < numberOfSelected {
            cell.selectButton.isSelected = true
            currentNumberOfSelected += 1
            rightButton.setTitle("选择(\(currentNumberOfSelected))", for: UIControlState())
        }
        else {
            showError()
        }
        selectedAsset[indexPath.row] = cell.selectButton.isSelected
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! QYPhotosCell
        let option = PHImageRequestOptions()
        option.version = PHImageRequestOptionsVersion.unadjusted
        option.deliveryMode = PHImageRequestOptionsDeliveryMode.opportunistic
        option.resizeMode = PHImageRequestOptionsResizeMode.fast
        let imageManager = PHImageManager.default()
        imageManager.requestImage(for: photos.object(at: indexPath.row), targetSize: CGSize(width: screenWidth, height: screenHeight), contentMode: PHImageContentMode.aspectFit, options: option) { (image, info) in
            DispatchQueue.main.async(execute: { 
                cell.imageView.image = image
            })
        }
        return cell
    }
    
}


